package com.hzlx.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TokenService {
    @Value("${security.key}")
    private  String key = "SuccessisnotfinalfailureisnotfatalItisthecouragetocontinuethatcounts"; // 生产环境需加密存储
    @Value("${expire.date}")
    private  long expireDate = 864_000_000; // 10天
    public String generateToken(String username, List<String> authorities){
        return Jwts.builder()
                .setSubject(username)        //用户账户
                .claim("authorities", authorities)//权限
                .setIssuedAt(new Date())
                                            //当前时间
                .setExpiration(new Date(System.currentTimeMillis() + expireDate))//设置令牌的过期时间
                .signWith(SignatureAlgorithm.HS256, key)//设置签名算法和密钥
                .compact();
    }
    //解析令牌
    public Claims validateToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build().parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    public String getUsernameFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(key)       // 设置签名密钥
                .parseClaimsJws(token)           // 解析并验证JWT
                .getBody()                       // 获取令牌载荷（Claims）
                .getSubject();                   // 获取subject声明
    }
}
